package com.yc.demo.demo;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

/**
 * 文件上传的Servlet
 */
@WebServlet("/upload.s")
// 文件上传必须添加注解, 属性用于控制文件上传的大小，数量，默认存储路径
@MultipartConfig()
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		// 接收浏览器发送过来文件, file是文件的字段（参数）名
		Part p = request.getPart("file");
		// 获取提交文件名
		String filename = p.getSubmittedFileName();
		
		// 获取应用上下文对象
	    // 生命周期长， 作用域广
		ServletContext application = this.getServletContext();
		//application = request.getServletContext();
		//application = request.getSession().getServletContext();
		// 根据web路径转成 真实路径 /login.html  => d:/.../login.html
		String realPath = application.getRealPath("/demo");
		System.out.println(realPath);
		// 保存文件
		p.write(realPath + "/" + filename);
		
		// response.getWriter().append("file upload success");
		
		String webpath = "/demo/" + filename;
		
		String json = "{ \"code\" : \"1\", \"msg\" : \"上传成功！\""
				+ ", \"path\" : \""+webpath+"\"}";
		
		response.getWriter().append(json);
		
		
		
		
		
	}

}
